const router = require('koa-router')()
const Leave = require('../modules/LeaveSchema')
const Dept = require('../modules/DeptSchema')
const util = require('../utils/util.js')
const jwt = require('jsonwebtoken')
router.prefix('/leave')

/**@type 申请列表、审核列表 */
router.get('/list', async (ctx) => {
  const { applyState, type, pageNum, pageSize } = ctx.request.query
  let auth = ctx.request.headers.authorization
  const { page, skipIndex } = util.pager({ pageNum, pageSize })
  const token = auth.split(' ')[1]
  const { data } = await jwt.verify(token, 'abizuis')
  try {
    let params = {}
    /** 如果是审核,
     * 查询当前审核人是否是自己，并且审批状态为待审批和审批中
     * 状态不为待审批,审批流内部必须包括我
     * 审批状态为0,查询全部但是得有我
     * */
    if (type == 'approve') {
      if (applyState == 1 || applyState == 2) {
        params.curAuditUserName = data.userName
        params.$or = [{ applyState: 1 }, { applyState: 2 }]
      } else if (applyState > 2) {
        params = { 'auditFlows.userId': data.userId, applyState }
      } else {
        params = { 'auditFlows.userId': data.userId }
      }
    } else {
      if (applyState) params.applyState = applyState
      params = {
        'applyUser.userId': data.userId,
      }
    }
    const query = Leave.find(params)
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await Leave.countDocuments(params)
    ctx.body = util.success({
      page: {
        ...page,
        total,
      },
      list,
    })
  } catch (error) {
    ctx.body = util.fail(`${error.stack}`)
  }
})

/**
 * @type 增删
 */
router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body

  let auth = ctx.request.headers.authorization
  const token = auth.split(' ')[1]
  const { data } = await jwt.verify(token, 'abizuis')
  try {
    if (action == 'create') {
      /** 创建申请单号 */
      let orderNo = 'XJ'
      orderNo += util.formateDate(new Date(), 'yyyyMMdd')
      const total = await Leave.countDocuments()
      params.orderNo = orderNo + total
      /** 根据当前用户获取上级部门负责人 */
      let id = data.deptId.pop()
      let dept = await Dept.findById(id)
      /** 获取人事部门和财富部门负责人信息 */
      let userList = await Dept.find({
        deptName: { $in: ['人事部门', '财务部门'] },
      })
      let auditUser = dept.userName
      /** 完整审批流 */
      let auditFlows = [
        {
          userId: dept.userId,
          userName: dept.userName,
          userEmail: dept.userEmail,
        },
      ]
      userList.map((item) => {
        auditFlows.push({
          userId: item.userId,
          userName: item.userName,
          userEmail: item.userEmail,
        })
        auditUser += ',' + item.userName
      })
      params.auditUser = auditUser
      /** 当前审批人 */
      params.curAuditUserName = dept.userName
      /** 审批流 */
      params.auditFlows = auditFlows
      /** 审批日志 */
      params.auditLogs = []
      /** 当前申请用户*/
      params.applyUser = {
        userId: data.userId,
        userName: data.userName,
        userEmail: data.userEmail,
      }
      await Leave.create(params)
      ctx.body = util.success({}, '申请成功')
    } else if (action == 'delete') {
      await Leave.findByIdAndUpdate(_id, { applyState: 5 })
      ctx.body = util.success({}, '操作成功')
    }
  } catch (error) {
    ctx.body = util.fail(`error=>${error.stack}`)
  }
})

/**
 * @type 审批
 */
router.post('/approve', async (ctx) => {
  const { action, _id, remark } = ctx.request.body
  let auth = ctx.request.headers.authorization
  const token = auth.split(' ')[1]
  const { data } = await jwt.verify(token, 'abizuis')
  /**
   * 如果是驳回，则直接修改葬台为拒绝
   * 如果是批准，则先判断审批流长度与日志长度是否相等,如果相等则已被处理
   * 如果当前审批流长度 = 日志长度+1 则代表最后一级处理成功
   * 如果审批流长度大于日志长度，则修改状态为审批中，并且将当前审批人改为下一级
   * 如果都不是则通过
   */
  let params = {}
  try {
    let doc = await Leave.findById(_id)
    let auditLogs = doc.auditLogs || []
    if (action == 'bh') {
      params.applyState = 3
    } else {
      if (doc.auditFlows.length == doc.auditLogs.length) {
        ctx.body = util.success('当前申请单已处理，请勿重复处理')
        return
      } else if (doc.auditFlows.length == doc.auditLogs.length + 1) {
        params.applyState = 4
      } else if (doc.auditFlows.length > doc.auditLogs.length) {
        params.applyState = 2
        params.curAuditUserName =
          doc.auditFlows[doc.auditLogs.length + 1].userName
      }
    }
    auditLogs.push({
      userId: data.userId,
      userName: data.userName,
      createTime: new Date(),
      remark,
      action: action == 'bh' ? '审核拒绝' : '审核通过',
    })
    params.auditLogs = auditLogs
    let res = await Leave.findByIdAndUpdate(_id, params)
    ctx.body = util.success({}, '操作成功')
  } catch (error) {
    ctx.body = util.fail(`error=>${error.stack}`)
  }
})

/** 审批通知 */
router.get('/count', async (ctx) => {
  let auth = ctx.request.headers.authorization
  const token = auth.split(' ')[1]
  const { data } = await jwt.verify(token, 'abizuis')
  let params = {}
  try {
    /** 当前审批人是自己才会获取通知 */
    params.curAuditUserName = data.userName
    params.$or = [{ applyState: 1 }, { applyState: 2 }]
    let total = await Leave.countDocuments(params)
    ctx.body = util.success(total)
  } catch (error) {
    ctx.body = util.fail(`error=>${error.message}`)
  }
})
module.exports = router
